package com.cloudspace.yunloan.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;


import com.cloudspace.yunloan.cropimage.CropImageActivity;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class PictureActivityUtil {

    public static final int MYSONG = 30;
    public static final int HEADPHOTO = 105;
    public static final String BACKGROUND = "background";

    /**
     * 用来标识请求照相功能的activity
     */
    public static final int CAMERA_WITH_DATA = 101;
    /**
     * 用来标识请求gallery的activity
     */
    public static final int PHOTO_PICKED_WITH_DATA = 201;

    /**
     * 图片裁剪
     */
    public static final int PHOTO_CROP = 301;

    /**
     */
    public static final int FINISH_UPLOAD = 401;
    //    /**
//     * 拍照的照片存储位置
//     */
//    public static final int VIEW_PICTURE = 1002;
    private static final File PHOTO_DIR = new File(
            Environment.getExternalStorageDirectory() + "/DCIM/Camera/");

    private static File mCurrentPhotoFile;// 照相机拍照得到的图片

    /**
     * 得到本地图片路径
     *
     * @return
     */
    public static File getCurrentPhotoFile() {
        if (mCurrentPhotoFile == null) {
            makePhotoDir();
            mCurrentPhotoFile = new File(PHOTO_DIR, genPhotoName());
            if (!mCurrentPhotoFile.exists())
                try {
                    mCurrentPhotoFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return mCurrentPhotoFile;
    }

    private static String genPhotoName() {
        return UUID.randomUUID() + "photo.jpg";
    }

    private static String genCropPhotoName() {
        return UUID.randomUUID() + "crop_photo.jpg";
    }

    /**
     * 开始启动照片选择框
     *
     * @param context
     * @param iscrop  是否裁剪
     */
    public static void doPickPhotoAction(final Activity context, final int requestCode, String title, String[] arrray) {
        MMAlert.showAlert(context,
                arrray,
                new ActionSheet.SimpleActionSheetListener() {
                    @Override
                    public void onItemClick(ActionSheet actionSheet, int index) {
                        switch (index) {
                            case 0: {
                                if (SDCardSizeUtil.isSdCardExist()) {// 判断是否有SD卡
                                    doTakePhoto(context, requestCode);// 用户点击了从照相机获取
                                } else {
                                    // AlertUtil.showToast(dialogContext, "没有找到SD卡");
                                }
                                break;
                            }
                            case 1:
                                doPickPhotoFromGallery(context, requestCode);// 从相册中去获取
                                break;
                        }
                    }
                }, title
        );
    }

    /**
     * 拍照获取图片
     */
    public static void doTakePhoto(Activity context, final int requestCode) {
        try {
            makePhotoDir();
            mCurrentPhotoFile = new File(PHOTO_DIR, genPhotoName());// 给新照的照片文件命名
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhotoFile));
            context.startActivityForResult(intent, requestCode);//CAMERA_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context.getApplicationContext(), "没有本地SD卡", Toast.LENGTH_LONG).show();

        }
    }

    /**
     * 请求Gallery相册程序
     *
     * @param context
     * @param iscrop
     */
    public static void doPickPhotoFromGallery(Context context, final int requestCode) {
        makePhotoDir();
        try {
//			Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
//			getImage.addCategory(Intent.CATEGORY_OPENABLE);
            Intent intent = new Intent(Intent.ACTION_PICK);
//            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            ((Activity) context).startActivityForResult(intent, requestCode);//PHOTO_PICKED_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context.getApplicationContext(), "", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }


    /**
     * 所有图片裁剪回调
     *
     * @param context
     * @param uri
     * @param requestCode
     */
    public static void doCropPhoto(Activity context, Uri uri, int requestCode) {
        makePhotoDir();
        File cropFile = new File(PHOTO_DIR, genCropPhotoName());
        Uri cropUri = Uri.fromFile(cropFile);
        CropImageActivity.show(context, requestCode + PHOTO_CROP, uri, cropUri);
    }

    /**
     * 获取不裁剪时图片返回的路径
     *
     * @param activity
     * @param data
     * @return path
     */
    @SuppressWarnings("deprecation")
    public static String getNoCropPath(Activity activity, Intent data) {
        String path = null;
        if (data == null)
            return getCurrentPhotoFile().toString();
        Uri imageuri = data.getData();
        if (imageuri == null) {
            String str = data.getAction();
            if (StringUtil.isEmpty(str)) {
                return getCurrentPhotoFile().toString();
            }
            imageuri = Uri.parse(str);

        }
        if (imageuri == null) {
            return path;
        }

        String scheme = imageuri.getScheme();

        if ("content".equals(scheme)) {
            Cursor cursor = null;
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = activity.getContentResolver().query(imageuri, proj, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(proj[0]);
                path = cursor.getString(columnIndex);
                try {
                    //4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
                    if (Integer.parseInt(Build.VERSION.SDK) < 14) {
                        cursor.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if ("file".equals(scheme)) {
            path = imageuri.getPath();
        }
        return path;
    }

    public static String getCropPath(Intent data) {
        Uri outCropImg = data.getParcelableExtra(CropImageActivity.RESULT_OUTPUT_PATH);
        if (outCropImg == null) {
            return getCurrentPhotoFile().getAbsolutePath();
        }
        return outCropImg.getPath();
    }

    private static void makePhotoDir() {
        try {
            if (!PHOTO_DIR.exists()) {
                PHOTO_DIR.mkdirs();// 创建照片的存储目录
            }
        } catch (Exception e) {
        }
    }

}
